/*
 * Copyright (C) 2008 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jbh.zxinglibrary;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.zxing.Result;
import com.jbh.zxinglibrary.utils.Constant;
import com.jbh.zxinglibrary.zxing.ScanListener;
import com.jbh.zxinglibrary.zxing.ScanManager;
import com.jbh.zxinglibrary.zxing.decode.DecodeThread;
import com.jbh.zxinglibrary.zxing.decode.Utils;
import java.util.regex.Pattern;


/**
 *
 * 二维码扫描使用
 *
 */
public final class CommonScanActivity extends AppCompatActivity implements ScanListener, View.OnClickListener {


    private SurfaceView scanPreview = null;
    private View scanContainer;
    private View scanCropView;
    private ImageView scanLine;
    private ScanManager scanManager;
    private TextView iv_light;
    private TextView qrcode_g_gallery;
    private TextView qrcode_ic_back;
    private final int PHOTOREQUESTCODE = 1111;
    private Button rescan;
    private ImageView scan_image;
    private int scanMode;//扫描模型（条形，二维码，全部）
    private TextView scan_hint;
    private TextView tv_scan_result;


    @Override
    protected void onCreate( Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = getWindow();
//        window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_scan_code);
        init(this);
        initView();
        key = getIntent().getStringExtra(RESULT_KEY);
    }


    /**
     * 初始化
     *
     * @param activity
     */
    private void init(Activity activity){
        if (Build.VERSION.SDK_INT>=19){
            if (Build.VERSION.SDK_INT >= 21) {
                View decorView =activity. getWindow().getDecorView();
                int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
                decorView.setSystemUiVisibility(option);
                activity.getWindow().setStatusBarColor(Color.TRANSPARENT);
            }else {
                //透明状态栏
                activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                //透明导航栏
//            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            }
        }
    }


   public void initView() {
       scanMode=getIntent()
               .getIntExtra(Constant.REQUEST_SCAN_MODE,
                       Constant.REQUEST_SCAN_MODE_ALL_MODE);
         rescan=findViewById(R.id.service_register_rescan);
         scan_image=findViewById(R.id.scan_image);
         scan_hint=findViewById(R.id.scan_hint);
         tv_scan_result=findViewById(R.id.tv_scan_result);

        switch (scanMode){
            case DecodeThread.BARCODE_MODE:
                scan_hint.setText(R.string.scan_barcode_hint);
                break;
            case DecodeThread.QRCODE_MODE:
                scan_hint.setText(R.string.scan_qrcode_hint);
                break;
            case DecodeThread.ALL_MODE:
                scan_hint.setText(R.string.scan_allcode_hint);
                break;
        }


        RelativeLayout sao_kuang = findViewById(R.id.sao_kuang);
        RelativeLayout top_mask = findViewById(R.id.top_mask);
        RelativeLayout bottom_mask = findViewById(R.id.bottom_mask);

        float density = getResources().getDisplayMetrics().density;

       int h = getResources().getDisplayMetrics().heightPixels;
       int w = (int) (getResources().getDisplayMetrics().widthPixels- density*68+0.5f);
       int h1 =( h - w)/2;


       ViewGroup.LayoutParams p = sao_kuang.getLayoutParams();
       ViewGroup.LayoutParams p1 = top_mask.getLayoutParams();
       ViewGroup.LayoutParams p2= bottom_mask.getLayoutParams();
       p.height = w ;
       p1.height = h1;
       p2.height = h1;
       sao_kuang.setLayoutParams(p);
       top_mask.setLayoutParams(p1);
       bottom_mask.setLayoutParams(p2);


       scanPreview =  findViewById(R.id.capture_preview);
       scanContainer = findViewById(R.id.capture_container);
       scanCropView = findViewById(R.id.capture_crop_view);


        scanLine =  findViewById(R.id.capture_scan_line);
        qrcode_g_gallery =  findViewById(R.id.qrcode_g_gallery);
        qrcode_g_gallery.setOnClickListener(this);
        qrcode_ic_back =  findViewById(R.id.qrcode_ic_back);
        qrcode_ic_back.setOnClickListener(this);
        iv_light =  findViewById(R.id.iv_light);
        iv_light.setOnClickListener(this);
        rescan.setOnClickListener(this);
//        authorize_return.setOnClickListener(this);
        //构造出扫描管理器
        scanManager = new ScanManager(this, scanPreview, scanContainer, scanCropView, scanLine, scanMode,this);
    }


    @Override
    public void onResume() {
        super.onResume();
        scanManager.onResume();
        rescan.setVisibility(View.INVISIBLE);
        scan_image.setVisibility(View.GONE);
    }




    @Override
    public void onPause() {
        super.onPause();
        scanManager.onPause();
    }




    /**
     * 扫描成功后，扫描器不会再连续扫描，如需连续扫描，调用reScan()方法。
     *
     * scanManager.reScan();
     */
    @Override
    public void scanResult(Result rawResult, Bundle bundle) {
        if (!scanManager.isScanning()) { //如果当前不是在扫描状态
            //设置再次扫描按钮出现
            rescan.setVisibility(View.VISIBLE);
            scan_image.setVisibility(View.VISIBLE);
            Bitmap barcode = null;
            byte[] compressedBitmap = bundle.getByteArray(DecodeThread.BARCODE_BITMAP);
            if (compressedBitmap != null) {
                barcode = BitmapFactory.decodeByteArray(compressedBitmap, 0, compressedBitmap.length, null);
                barcode = barcode.copy(Bitmap.Config.ARGB_8888, true);
            }
            scan_image.setImageBitmap(barcode);
        }

        rescan.setVisibility(View.VISIBLE);
        scan_image.setVisibility(View.VISIBLE);
        tv_scan_result.setVisibility(View.VISIBLE);


        doTask(rawResult.getText());
    }



    /***
     * 扫描结果
     *
     *  if(scanMode == DecodeThread.BARCODE_MODE) 条形码
     *
     *  if(scanMode == DecodeThread.QRCODE_MODE) 二维码
     *
     * @param text
     */
    public static final String ACTION = "com.jbh.zxinglibrary.CommonScanActivity";
    public static final String RESULT_KEY = "result_key" ;
    public static final String SCAN_RESULT = "scan_result";
    public static final String REQUEST_CODE = "requestCode";

    String key = "" ;

    private void doTask(String text) {
        Log.v("=====","=======扫码======"+text);
        /*是否为网址的正则表达式*/
        Pattern pattern = Pattern.compile("^([hH][tT]{2}[pP]://|[hH][tT]{2}[pP][sS]://)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\\/])+$");
        sendBroadcast(key,text);
        finish();
    }



    /**
     * 发送消息
     *
     * @param val
     */
    public void sendBroadcast(String key,String val){
        sendBroadcast(new Intent(ACTION)
                .putExtra(RESULT_KEY,key)
                .putExtra(SCAN_RESULT,val));
    }



    void startScan() {
        if (rescan.getVisibility() == View.VISIBLE) {
            rescan.setVisibility(View.INVISIBLE);
            scan_image.setVisibility(View.GONE);
            scanManager.reScan();
        }
    }



    @Override
    public void scanError(Exception e) {
        Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
        //相机扫描出错时
        if(e.getMessage()!=null&&e.getMessage().startsWith("相机")){
            scanPreview.setVisibility(View.INVISIBLE);
        }
    }




    public void showPictures(int requestCode) {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent, requestCode);
    }




    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String photo_path;
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PHOTOREQUESTCODE:
                    String[] proj = {MediaStore.Images.Media.DATA};
                    Cursor cursor = this.getContentResolver().query(data.getData(), proj, null, null, null);
                    if (cursor.moveToFirst()) {
                        int colum_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                        photo_path = cursor.getString(colum_index);
                        if (photo_path == null) {
                            photo_path = Utils.getPath(getApplicationContext(), data.getData());
                        }
                        scanManager.scanningImage(photo_path);
                    }
            }
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.qrcode_g_gallery) {
            showPictures(PHOTOREQUESTCODE);
        } else if (id == R.id.iv_light) {
            scanManager.switchLight();
        } else if (id == R.id.qrcode_ic_back) {
            finish();
        } else if (id == R.id.service_register_rescan) {//再次开启扫描
            startScan();
        }
    }
}